@extends('layout.app')
@section('main-content')
    <h1 class="select-none text-center text-4xl mb-10">Add Contact</h1>
    <div class="flex gap-10 items-center flex-col">
        <div class="select-none flex w-[100%] gap-3">
            <div class="basis-3/10 self-stretch">
                <h2 class="text-center text-xl">Contact</h2>
                <form action="{{route('create-contact')}}" id="contact-form" class="w-[100%]" method="get">
                    <div class="mt-5">
                        <label for="" class="block">First Name</label>
                        <input type="text" name="first_name" class="border @if($errors->has('first_name')) border-red-500 @endif rounded px-2 py-1 w-[100%]" value="{{old('first_name')}}">
                    </div>
                    <div class="mt-5">
                        <label for="" class="block">Last Name</label>
                        <input type="text" name="last_name" class="border rounded px-2 py-1 w-[100%]" value="{{old('last_name')}}">
                    </div>
                    <div class="mt-5">
                        <label for="" class="block">Title</label>
                        <input type="text" name="title" list="titles" class="border rounded px-2 py-1 w-[100%]" value="{{old('title')}}">
                        <datalist id="titles">
                            @foreach($titles as $title)
                                <option value="{{$title}}"></option>
                            @endforeach
                        </datalist>
                    </div>
                </form>
            </div>

            <div class="basis-2/5 self-stretch">
                <h2 class="text-center text-xl">Contact Records</h2>
                <div class="flex mt-5 gap-1">
                    <div>
                        <label for="" class="block">Contact Method</label>
                        <input class="input-method border rounded px-2 py-1" type="text" list="methods">
                        <datalist id="methods">
                            @foreach($methods as $method)
                                <option data-method-id="{{$method->id}}" value="{{$method->name}}"></option>
                            @endforeach
                        </datalist>
                    </div>
                    <div>
                        <label for="" class="block">Record</label>
                        <input class="input-record border rounded px-2 py-1" type="text">
                    </div>
                    <div>
                        <button class="button-add-method border rounded px-2 py-1 mt-6">Add</button>
                    </div>
                </div>
                <div class="mt-2">
                    <table class="w-[100%]">
                        <thead>
                        <tr>
                            <th>Method</th>
                            <th>Record</th>
                        </tr>
                        </thead>
                        <tbody class="table-records">
                        <tr class="contact-record">
                            <td>Email</td>
                            <td>
                                <p>
                                    <span>abc@gmail.com</span>
                                    <button><i
                                            class="icon-delete-record fa-regular fa-trash-can text-gray-300 hover:text-red-600"
                                            title="Delete"></i></button>
                                    <button><i
                                            class="icon-edit-record fa-regular fa-edit ml-3 text-gray-300 hover:text-green-600"
                                            title="Edit"></i></button>
                                </p>
                                <p>
                                    <span>def@gmail.com</span>
                                    <button><i
                                            class="icon-delete-record fa-regular fa-trash-can text-gray-300 hover:text-red-600"
                                            title="Delete"></i></button>
                                    <button><i
                                            class="icon-edit-record fa-regular fa-edit ml-3 text-gray-300 hover:text-green-600"
                                            title="Edit"></i></button>
                                </p>
                            </td>
                        </tr>
                        <tr class="contact-record">
                            <td>Mobile</td>
                            <td>
                                <p>
                                    <span>15634525879</span>
                                    <button><i
                                            class="icon-delete-record fa-regular fa-trash-can text-gray-300 hover:text-red-600"
                                            title="Delete"></i></button>
                                    <button><i
                                            class="icon-edit-record fa-regular fa-edit ml-3 text-gray-300 hover:text-green-600"
                                            title="Edit"></i></button>
                                </p>
                            </td>
                        </tr>
                        </tbody>
                    </table>
                </div>
            </div>

            <div class="group-box basis-3/10 self-stretch flex gap-1">
                <div class="mt-5 self-stretch basis-1/2">
                    <h2 class="text-center text-xl">Groups</h2>
                    <div id="groups" class="border min-h-[80%] w-[100%] pb-10 h-[auto]">
                        <ul>
                            @foreach($groups as $group)
                                <li draggable="true" data-id="{{$group->id}}"
                                    class="list-none relative bg-gray-100 border rounded px-4 py-1 group-option">
                                    <span class="group-name">{{$group->name}}</span>
                                    <button><i
                                            class="icon-delete-group fa-regular fa-trash-can text-gray-300 hover:text-red-600"
                                            title="Delete"></i></button>
                                    <button><i
                                            class="icon-edit-group fa-regular fa-edit text-gray-300 hover:text-green-600"
                                            title="Edit"></i></button>
                                </li>
                            @endforeach
                        </ul>
                    </div>

                </div>
                <div class="mt-5 self-stretch basis-1/2">
                    <h2 class="text-center text-xl">In Groups</h2>
                    <div id="joined-group-list" class="border min-h-[80%] h-[auto] pb-10 w-[100%]">
                        <ul>

                        </ul>
                    </div>
                    <div class="mt-2 self-stretch">
                        <input type="text" class="border w-[100%] rounded py-1 px-2" id="new-group">
                        <button class="add-group border rounded py-1 px-2">Add Group</button>
                    </div>
                </div>
            </div>
        </div>
        <div>
            <button
                class="submit border rounded bg-blue-100 text-gray-400 hover:text-gray-100 hover:bg-blue-500 px-2 py-1 text-2xl">
                Submit
            </button>
        </div>
    </div>
    @if(old('joined_group_names'))
    @foreach(old('joined_group_names') as $name)
        <p>{{$name}}</p>
    @endforeach
    @endif
    @if($errors->any())
        <ul>
            @foreach($errors->all() as $error)
            <li>{{$error}}</li>
                @endforeach
        </ul>
        @endif
    <script>
        //变量
        let currentEditGroup;
        let currentEditRecord;
        let currentEditMethod;
        let modifiedGroups = []
        let deletedGroupIds = []
        let addedGroupNames = []
        //实用方法
        const formatMethod = (name) => {
            return name.trim().split(/\s+/).map((w) => capitalize(w)).join(' ');
        }
        const capitalize = (word) => {
            const w = word.toLowerCase()
            return w[0].toUpperCase() + w.substr(1);
        }

        function groupExists(name) {
            let result = false
            $$('#groups ul li span').forEach(op => {
                if (name.toLowerCase() == op.innerText.toLowerCase()) {
                    result = true;
                }
            })
            return result;
        }

        //新增组
        $('.add-group').addEventListener('click', e => {
            let name = $('input#new-group').value
            if($('.add-group').innerText==="Add Group"){
                if (!groupExists(name) && name !== "") {
                    let option =`
                    <li draggable="true" data-id="0"
                        class="list-none relative bg-gray-100 border rounded px-4 py-1 group-option">
                        <span class="text-red-500">${name}</span>
                        <button><i
                            class="icon-delete-group fa-regular fa-trash-can text-gray-300 hover:text-red-600"
                            title="Delete"></i></button>
                        <button><i
                            class="icon-edit-group fa-regular fa-edit text-gray-300 hover:text-green-600"
                            title="Edit"></i></button>
                    </li>
                    `
                    addedGroupNames.push(name)
                    $('#groups ul').innerHTML += option;
                    $('input#new-group').value=""
                }
            }else {
                currentEditGroup.innerText=name;
                $('.add-group').innerText="Add Group"
                $('input#new-group').value=""
                modifiedGroups.push(
                    [
                        currentEditGroup.parentNode.dataset.id,
                        name
                    ]
                )
            }
        })
        //双击加入组
        document.addEventListener('dblclick', e => {
            if (e.target.classList.contains("group-option")) {
                if(e.target.parentNode.parentNode.id==='groups'){
                    $('#joined-group-list').children[0].append(e.target);
                }else if(e.target.parentNode.parentNode.id==='joined-group-list'){
                    $('#groups').children[0].append(e.target);
                }
            }
        })
        //draggable拖拽
        let dragSource
        document.addEventListener("dragstart",e=>{
            if(e.target.classList.contains('group-option')){
                dragSource=e.target;
                e.target.style.opacity='0.5'
            }
        })
        document.addEventListener("dragend",e=>{
            if(e.target.classList.contains('group-option')){
                dragSource=null;
                e.target.style.opacity='1'
            }
        })
        document.addEventListener('dragover',e=>{
            if(e.target.id==="groups"){
                e.preventDefault()
            }
            if(e.target.id==="joined-group-list"){
                e.preventDefault()
            }
        })
        document.addEventListener("drop",e=>{
            if(e.target.id==="groups"){
                e.target.children[0].append(dragSource)
            }
            if(e.target.id==="joined-group-list"){
                e.target.children[0].append(dragSource)
            }
        })
        //编辑和删除组
        $('.group-box').addEventListener('click',e=>{
            let currentGroup = e.target.parentNode.parentNode.children[0];
            if (e.target.classList.contains('icon-edit-group')) {//点击编辑按钮
                currentEditGroup = currentGroup;
                $('input#new-group').value=currentGroup.innerText;
                $('.add-group').innerText = "OK"
            } else if (e.target.classList.contains('icon-delete-group')) {//点击删除按钮
                let parent = currentGroup.parentNode
                Swal.fire({
                    title: 'Are you sure?',
                    text: "You won't be able to revert this!",
                    type: 'warning',
                    showCancelButton: true,
                    confirmButtonColor: '#3085d6',
                    cancelButtonColor: '#d33',
                    confirmButtonText: 'Yes, delete it!',
                    allowOutsideClick: false
                }).then((result) => {
                    if (result.value) {
                        parent.remove();
                        const id = parent.dataset.id
                        if(id>0){
                            deletedGroupIds.push(id)
                        }
                    }
                })
            }
        })

        //点击添加按钮事件
        $('.button-add-method').addEventListener('click', e => {
            let inputMethod = $('.input-method').value
            let inputRecord = $('.input-record').value
            //添加情况
            if ($('.button-add-method').innerText === "Add") {
                let records = $$('.table-records tr');
                let methodList = []
                let isNew;
                if (inputMethod !== "" && inputRecord !== "") {
                    records.forEach(e => {
                        let method = e.childNodes[1].innerText
                        methodList.push(method);
                        //methods.push(method);
                        if (method === formatMethod(inputMethod)) {
                            let recordHtml = `
                         <p>
                            <span>${inputRecord}</span>
                            <button><i class="icon-delete-record fa-regular fa-trash-can text-gray-300 hover:text-red-600"
                                       title="Delete"></i></button>
                            <button><i class="icon-edit-record fa-regular fa-edit ml-3 text-gray-300 hover:text-green-600"
                                       title="Edit"></i></button>
                        </p>
                `
                            e.childNodes[3].innerHTML += recordHtml;
                        }
                    })
                    //如果方法列表没有包含输入的方法，则isNew为true
                    isNew = !methodList.includes(formatMethod(inputMethod));
                    if (isNew) {
                        let tr = `
                <tr class="contact-record">
                    <td>${formatMethod(inputMethod)}</td>
                    <td>
                       <p>
                        <span>${inputRecord}</span>
                        <button><i class="icon-delete-record fa-regular fa-trash-can text-gray-300 hover:text-red-600"
                                   title="Delete"></i></button>
                        <button><i class="icon-edit-record fa-regular fa-edit ml-3 text-gray-300 hover:text-green-600"
                                   title="Edit"></i></button>
                        </p>
                    </td>
                </tr>
                `
                        $(".table-records").innerHTML += tr;
                    }
                }
            } else if ($('.button-add-method').innerText === "OK") {//处理修改的情况
                //当前点击编辑或删除时对应的元素,其innerText即当前记录内容
                currentEditMethod.innerText = inputMethod;
                currentEditRecord.innerText = inputRecord;
                $('.button-add-method').innerText = "Add"

            }
            //清空值
            $('.input-method').value = '';
            $('.input-record').value = '';
        })
        //表格内的点击事件
        $('.table-records').addEventListener('click', e => {
            let currentRecord
            let currentMethod
            //点击修改,删除icon的事件
            if (e.target.localName === "i") {
                //当前点击编辑或删除时对应的元素,其innerText即当前记录内容
                currentRecord = e.target.parentNode.parentNode.children[0];
                currentMethod = e.target.parentNode.parentNode.parentNode.parentNode.children[0];
                if (e.target.classList.contains('icon-edit-record')) {//点击编辑按钮
                    currentEditRecord = currentRecord;
                    currentEditMethod = currentMethod;
                    $('.input-method').value = currentMethod.innerText;
                    $('.input-record').value = currentRecord.innerText;
                    $('.button-add-method').innerText = "OK"
                } else if (e.target.classList.contains('icon-delete-record')) {//点击删除按钮
                    let parent = currentRecord.parentNode.parentNode
                    Swal.fire({
                        title: 'Are you sure?',
                        text: "You won't be able to revert this!",
                        type: 'warning',
                        showCancelButton: true,
                        confirmButtonColor: '#3085d6',
                        cancelButtonColor: '#d33',
                        confirmButtonText: 'Yes, delete it!',
                        allowOutsideClick: false
                    }).then((result) => {
                        if (result.value) {
                            currentRecord.parentNode.remove();
                            if (parent.children.length === 0) {
                                parent.parentNode.remove();
                            }
                        }
                    })
                }
            }
        })

        function getContactRecords(){
            let records = []
            $$(".contact-record").forEach((el)=>{
                 let method = el.children[0].innerText
                console.log(method)
                 el.children[1].querySelectorAll("p").forEach((p)=>{
                     let record = p.querySelector("span").innerText
                     records.push([method,record])
                 })
            })
            console.log(records)
            return records
        }
        function getJoinedGroups(){
            let groups = []
            $$("#joined-group-list ul li").forEach((el)=>{
                groups.push([
                    el.dataset.id,
                    el.querySelector("span").innerText
                ])
            })
            return groups;
        }

        $("button.submit").addEventListener('click',(e)=>{
            let fm = $("#contact-form")
            getContactRecords().forEach((r,idx)=>{
                let input1 = document.createElement("input")
                input1.type = 'hidden'
                input1.name = `methods[${idx}]`
                input1.value = r[0]
                fm.append(input1)
                let input2 = document.createElement("input")
                input2.type = 'hidden'
                input2.name = `records[${idx}]`
                input2.value = r[1]
                fm.append(input2)
            })
            deletedGroupIds.forEach((gid)=>{
                let input = document.createElement("input")
                input.type = 'hidden'
                input.name = `deleted_group_ids[]`
                input.value = gid
                fm.append(input)
            })
            modifiedGroups.forEach((g,idx)=>{
                let input1 = document.createElement("input")
                input1.type = 'hidden'
                input1.name = `modified_group_ids[${idx}]`
                input1.value = g[0]
                fm.append(input1)
                let input2 = document.createElement("input")
                input2.type = 'hidden'
                input2.name = `modified_group_names[${idx}]`
                input2.value = g[1]
                fm.append(input2)
            })
            getJoinedGroups().forEach((g,idx)=>{
                let input1 = document.createElement("input")
                input1.type = 'hidden'
                input1.name = `joined_group_ids[${idx}]`
                input1.value = g[0]
                fm.append(input1)
                let input2 = document.createElement("input")
                input2.type = 'hidden'
                input2.name = `joined_group_names[${idx}]`
                input2.value = g[1]
                fm.append(input2)
            })
            addedGroupNames.forEach((name)=>{
                let input = document.createElement("input")
                input.type = 'hidden'
                input.name = `added_group_names[]`
                input.value = name
                fm.append(input)
            })

            fm.submit();
        })
    </script>
@endsection
